<template>
  <div>
    <div id="chart" style="height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'; // 引入 ECharts
import { getLineChartData } from '@/api'; // 引入获取堆叠折线图数据的接口

export default {
  //props: ['projectName'], // 接收父组件传入的项目名
  data() {
    return {
      chart: null,
      chartData: {}, // 存储后端数据
      tooltipData: [], // 鼠标悬停时显示的额外信息
    };
  },
  mounted() {
    this.initChart(); // 初始化图表
    this.fetchChartData(); // 获取图表数据
  },
  methods: {
    // 初始化 ECharts 图表
    initChart() {
      this.chart = echarts.init(document.getElementById('chart')); // 获取 DOM 节点并初始化图表
      this.chart.on('mouseover', this.handleMouseOver); // 鼠标悬停事件
    },
    // 获取图表数据并传递项目名
    fetchChartData() {
      const projectName = "项目管理系统"; //测试
      console.log('请求参数:', { projectName });
      // 发送带有项目名的请求
      // getLineChartData({ projectName: this.projectName })
      getLineChartData({ projectName }) // 将项目名称传递给后端
          .then((response) => {
            console.log('后端返回数据:', response);
            if (response.code === 200) {
              this.chartData = response.data; // 存储图表数据
              console.log('存储的图表数据:', this.chartData);
              this.updateChart(); // 更新图表
            } else {
              console.error("获取项目数据失败:", response.msg);
            }
          })
          .catch((error) => {
            console.error("获取图表数据失败:", error.response ? error.response.data : error.message);
          });
    },
    // 更新图表
    updateChart() {
      if (!this.chartData) {
        console.error('未能从后端数据中解析出 chartData 属性:', this.chartData);
        return;
      }

      const { contractAmount, outputValue, startDate, tasks, totalCost } = this.chartData;

      if (!startDate || !contractAmount || !outputValue || !totalCost || !tasks) {
        console.error('后端返回的数据不完整，无法渲染图表:', this.chartData);
        return;
      }

      const time = startDate;
      const contracts = contractAmount;
      const output = outputValue;
      const costs = totalCost;

      // 动态范围计算
      const maxDynamicValue = Math.max(...output, ...costs);
      const minDynamicValue = Math.min(...output, ...costs);
      const maxFixedValue = Math.max(...contracts);

      // 断点设置（跳过合同额与产值/成本间的空白）
      const breaks = [
        {
          startValue: Math.max(0, minDynamicValue), // 动态数据最大值以上开始
          endValue: Math.min(maxFixedValue, maxDynamicValue * 1.1), // 合同额以下结束
          interval: Math.ceil(maxDynamicValue / 5), // 动态生成刻度间隔
        },
      ];

      const option = {
        title: {
          text: `项目合同额、产值与成本变化折线图`,
          left: 'center', // 居中显示
          textStyle: {
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        color: ['#5470c6', '#91cc75', '#fac858'], // 自定义线条颜色
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.7)', // 半透明背景
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 12,
          },
          extraCssText: 'backdrop-filter: blur(10px); box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; padding: 12px;',
          formatter: (params) => {
            const data = params[0].data; // 当前折线的数据点
            const contractAmount = data.contractAmount || '无';
            const totalCost = data.totalCost || '无';
            const outputValue = data.outputValue || '无';
            const taskDetail = this.tooltipData[data.index] || {}; // 获取对应的任务详情

            return `
          <div>
            <strong>日期：</strong>${params[0].axisValue}<br />
            <strong>合同额：</strong>${contractAmount}<br />
            <strong>成本：</strong>${totalCost}<br />
            <strong>产值：</strong>${outputValue}<br />
            <strong>任务名：</strong>${taskDetail.taskName || '无'}<br />
            <strong>人员：</strong>${taskDetail.memberName || '无'}<br />
            <strong>工时：</strong>${taskDetail.workHours || '无'}<br />
            <strong>月薪：</strong>${taskDetail.monthlySalary || '无'}
          </div>
        `;
          },
        },
        legend: {
          data: ['合同额', '产值', '成本'],
          left: '75%',
          textStyle: {
            fontSize: 12, // 调整文字大小
            color: '#333', // 调整文字颜色
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: { title: '导出为图片' },
          },
        },
        dataZoom: [
          {
            type: 'slider', // 滑动条
            start: 0, // 显示 0% ~ 100%
            end: 100,
          },
          {
            type: 'inside', // 鼠标滚动
            start: 0,
            end: 100,
          },
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: time, // x 轴时间数据
        },
        yAxis: {
          type: 'value',
          axisLine: { show: true, lineStyle: { color: '#333' } },
          axisLabel: { show: true, formatter: '{value}' },
          splitLine: { show: true, lineStyle: { type: 'dashed', color: '#ddd' } },
          min: Math.max(0, minDynamicValue * 0.9), // 最小值为动态区间的 90%
          max: maxFixedValue * 1.1, // 最大值为合同额的 110%
          axisBreaks: breaks, // 使用断点
        },
        series: [
          {
            name: '合同额',
            type: 'line',
            data: contracts.map((value, index) => ({
              value: value,
              contractAmount: value,
              outputValue: output[index],
              totalCost: costs[index],
              index,
            })),
          },
          {
            name: '产值',
            type: 'line',
            data: output.map((value, index) => ({
              value: value,
              contractAmount: contracts[index],
              outputValue: value,
              totalCost: costs[index],
              index,
            })),
          },
          {
            name: '成本',
            type: 'line',
            data: costs.map((value, index) => ({
              value: value,
              contractAmount: contracts[index],
              outputValue: output[index],
              totalCost: value,
              index,
            })),
          },
        ],
      };

      this.tooltipData = tasks.map((task, index) => ({
        taskName: task.taskName,
        memberName: task.memberName,
        workHours: task.workHours,
        monthlySalary: task.monthlySalary,
      }));

      this.chart.setOption(option);
    },

    // 处理鼠标悬停事件，显示对应的任务信息
    handleMouseOver(event) {
      const dataIndex = event.dataIndex;
      const taskDetail = this.tooltipData[dataIndex] || {};
      this.tooltipData[dataIndex] = taskDetail;
    },
  },
};
</script>

<style scoped>
#chart {
  width: 100%;
  height: 400px;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
</style>